package com.example.androidshixi;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.Date;
import java.util.List;

public class HeadlinesFragment extends Fragment {

    private ListView articleListView;
    private ArrayAdapter<Article> adapter;
    private UserSessionManager sessionManager;
    private ArticleViewModel articleViewModel;
    private boolean isFirstLoad = true;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_headlines, container, false);

        articleListView = view.findViewById(R.id.article_list_view);
        FloatingActionButton addArticleFab = view.findViewById(R.id.add_article_fab);
        sessionManager = new UserSessionManager(requireContext());
        articleViewModel = new ViewModelProvider(requireActivity()).get(ArticleViewModel.class);

        if (isFirstLoad) {
            initArticleList();
            isFirstLoad = false;
        }

        // 设置适配器
        adapter = new ArrayAdapter<Article>(requireContext(), R.layout.article_item, R.id.article_title_text_view, articleViewModel.getArticleList()) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                Article article = articleViewModel.getArticleList().get(position);
                ((TextView) view.findViewById(R.id.article_title_text_view)).setText(article.getTitle());
                ((TextView) view.findViewById(R.id.article_content_text_view)).setText(article.getContent());
                return view;
            }
        };
        articleListView.setAdapter(adapter);

        // 处理文章列表项点击事件
        articleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Article article = articleViewModel.getArticleList().get(position);
                Intent intent = new Intent(requireContext(), ArticleDetailActivity.class);
                intent.putExtra("title", article.getTitle());
                intent.putExtra("author", article.getAuthor());
                intent.putExtra("time", article.getTime().getTime());
                intent.putExtra("content", article.getContent());
                startActivity(intent);
            }
        });

        // 处理添加文章按钮点击事件
        addArticleFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAddArticleDialog();
            }
        });

        return view;
    }

    private void initArticleList() {
        if (articleViewModel.getArticleList().isEmpty()) {
            // 添加两个固定文章
            Date currentDate = new Date();
            String author = "默认作者";
            Article article1 = new Article("文章1标题", author, currentDate, "文章1内容");
            Article article2 = new Article("文章2标题", author, currentDate, "文章2内容");
            articleViewModel.addArticle(article1);
            articleViewModel.addArticle(article2);
        }
    }

    private void showAddArticleDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("添加文章");

        // 加载自定义布局
        View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_add_article, null);
        final EditText titleEditText = dialogView.findViewById(R.id.dialog_article_title);
        final EditText contentEditText = dialogView.findViewById(R.id.dialog_article_content);

        builder.setView(dialogView);

        // 设置确定按钮
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String title = titleEditText.getText().toString().trim();
                String content = contentEditText.getText().toString().trim();

                if (!title.isEmpty() &&!content.isEmpty()) {
                    String author = sessionManager.getLoggedInUsername();
                    Date currentDate = new Date();
                    String formattedDate = DateFormat.format("yyyy年MM月dd日", currentDate).toString();
                    Article newArticle = new Article(title, author, currentDate, content);
                    articleViewModel.addArticle(newArticle);
                    adapter.notifyDataSetChanged();
                } else {
                    // 提示用户输入有效信息
                    showErrorDialog();
                }
            }
        });

        // 设置取消按钮
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        // 显示对话框
        builder.create().show();
    }

    private void showErrorDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("错误");
        builder.setMessage("请输入有效的文章标题和内容");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showAddArticleDialog();
            }
        });
        builder.create().show();
    }

    // 添加公共方法来获取 articleList
    public List<Article> getArticleList() {
        return articleViewModel.getArticleList();
    }
}